package com.jy.project.service.imp;

import com.alibaba.fastjson.JSONObject;
import com.jy.project.constant.MaterialConstant;
import com.jy.project.controller.MatericalController;
import com.jy.project.domain.Apply;
import com.jy.project.domain.ApplyBorrow;
import com.jy.project.domain.ApplyHandover;
import com.jy.project.domain.User;
import com.jy.project.dto.*;
import com.jy.project.enums.ApplyTypeEnum;
import com.jy.project.enums.ApplyTypeMatericalEnum;
import com.jy.project.enums.QualityStatusEnum;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.*;
import com.jy.project.service.ApplyService;
import com.jy.project.service.imp.defult.DefaultApplyBusinessImp;
import com.jy.project.util.*;
import com.jy.project.vo.ApplyDeptAdminVO;
import com.jy.project.vo.ApplyQualitVO;
import com.jy.project.vo.ApplyUserVO;
import com.jy.project.vo.MaterialVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("applyHandoverServiceImpl")
@Slf4j
public class ApplyHandoverServiceImpl extends DefaultApplyBusinessImp implements ApplyService {

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private ApplyHandoverMapper applyHandoverMapper;


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;


    @Override
    public boolean insertApply(ApplyDTO dto) {
        dto.setApplyType(ApplyTypeEnum.HANDOVERL.getCode());
        Set<Integer> set = new HashSet<>();
        set.add(dto.getApplyType());
        dto.setExt(JSONObject.toJSONString(set));
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            boolean bl = this.insertApplyBusiness(dto);
            if (bl == false) {
                throw new BizException("申请交接单失败");
            }
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            throw  e;
        }
        dataSourceTransactionManager.commit(transactionStatus);
        return true;
    }

    @Override
    public List<ApplyQualitVO> listApplyQualityVO(ApplyQueryDTO dto) {

        return applyMapper.listApplyyQualityVO(dto);
    }

    @Override
    public List<ApplyDeptAdminVO> listDeptAdminApplyVO(ApplyDeptAdminQueryDTO dto) {
        return null;
    }

    @Override
    public boolean applyAdopt(ApplyAdoptDTO dto) {
        log.info("审批通过交接单");
        String applyNo = dto.getApplyNo();
        Apply apply = applyMapper.getApplyByApplyNo(applyNo);
        if (apply==null){
            throw  new BizException("申请单不存在");
        }
        String extHandoverApplyNo = apply.getExt();
        List<Apply> applyList = applyMapper.listApplyByExt(extHandoverApplyNo,ApplyTypeEnum.HANDOVERL.getCode());
        for (Apply ap : applyList) {
            String apNo = ap.getApplyNo();
            if (applyNo.equals(apNo)){
                continue;
            }
            Integer status = ap.getStatus();
            if (!status.equals(1)){
                log.info("extApplyNo {} 还没用通过"+apNo);
                return true;
            }
        }
        Example example =new Example(ApplyHandover.class);
        example.createCriteria().andEqualTo("applyNo",applyNo);
        List<ApplyHandover> applyHandovers = applyHandoverMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(applyHandovers)){
            throw  new BizException("数据不存在");
        }
        List<String> materialNos=new ArrayList<>();
        for (int i = 0; i < applyHandovers.size(); i++) {
            materialNos.add(applyHandovers.get(i).getMaterialNo());
        }
        ApplyUpdateDTO applyUpdateCollectDTO=new ApplyUpdateDTO();
        BeanUtils.copyProperties(apply,applyUpdateCollectDTO);
        String s = CommonStringUtils.toStr(materialNos);
        applyUpdateCollectDTO.setMaterialNos(s);
        applyUpdateCollectDTO.setUseStatus(1);
        return materialMapper.updateApplyUpdateCollectDTO(applyUpdateCollectDTO)>0;
    }

    @Override
    public boolean applyReject(ApplyAdoptDTO dto) {
        log.info("驳回交接单");
        return true;
    }

    @Override
    public ServiceResultUtils listMaterialDetailsVO(MaterialDetailsDTO dto) {
       return  null;
    }

    @Override
    public List<ApplyUserVO> listUserApplyVO(ApplyUserQueryDTO dto) {
        return null;
    }


    @Override
    public void checkApplyNo(String applyNo) {
        super.checkApplyNo(applyNo);
    }

    @Override
    public MaterialVO checkMaterialNo(String materialNo) {
        return super.checkMaterialNo(materialNo);
    }

    @Override
    public boolean insertApplyBusiness(ApplyDTO dto) {
        if (dto==null){
            throw new BizException("Apply对象为空");
        }
        checkApplyNo(dto.getApplyNo());
        //制单人
        String token = dto.getToken();
        User u = JwtUtils.verifyToken(token);
        Long id = u.getId();
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            throw  new BizException("用户信息可能找不到");
        }
        String[] checkMaterialNos = dto.getCheckMaterialNos();
        if (checkMaterialNos==null){
            throw  new BizException("没有选中信息");
        }
        if (checkMaterialNos.length<0){
            throw  new BizException("没有选中信息");
        }
        List<MaterialVO> materialVOS = checkMaterialNos(checkMaterialNos);
        if (materialVOS.isEmpty()){
            throw  new BizException("当前中不到使用的资产");
        }
        //使用人
        User useUser=null;
        if (dto.getUseUserId()!=null&&dto.getUseUserId()!=0) {
            useUser= userMapper.selectByPrimaryKey(dto.getUseUserId());
            if (useUser == null) {
                throw new BizException("使用者用户信息找不到");
            }
        }
        ApplyHandoverDTO applyHandoverDTO=(ApplyHandoverDTO)dto;
        Long adminUserId = applyHandoverDTO.getAdminUserId();
        if (adminUserId==null){
            throw  new BizException("交接管理管理员id不能为空");
        }

        //管理者
        User adminUser=null;
        if (adminUserId!=null&&adminUserId!=0) {
             adminUser = userMapper.selectByPrimaryKey(adminUserId);
            if (adminUser==null){
                throw  new BizException("交接管理管理员不存在或者已经被删除");
            }
        }
        //交接人
        Long handoverPersonUserId = applyHandoverDTO.getHandoverPersonUserId();
        if (handoverPersonUserId==null&&handoverPersonUserId==0) {
            throw  new BizException("交接人不存在");
        }
        User handoverPersonUser= userMapper.selectByPrimaryKey(handoverPersonUserId);
        if (handoverPersonUser == null) {
            throw new BizException("使用者用户信息找不到");
        }
        for (int i = 0; i < materialVOS.size(); i++) {
            Apply ay = this.create();
            ay.setApplyType(dto.getApplyType());
            ay.setName(ApplyTypeEnum.getValue(ay.getApplyType()));
            if (user!=null){
                ay.setApplicantCompanyNo(user.getCompanyNo());
                ay.setApplicantCompanyName(user.getCompanyName());
                ay.setApplicantDeptNo(user.getDeptNo());
                ay.setApplicantDeptName(user.getDeptName());
                ay.setApplicantUserId(user.getId());
                ay.setApplicantUserNickName(user.getNickName());
            }
            ay.setUseCompanyNo(useUser.getCompanyNo());
            ay.setUseCompanyName(useUser.getCompanyName());
            ay.setUseDeptNo(useUser.getDeptNo());
            ay.setUseDeptName(useUser.getDeptName());
            ay.setUseUserId(useUser.getId());
            ay.setUseNickName(useUser.getNickName());
            ay.setRemarks(dto.getRemarks());
            MaterialVO materialVO = materialVOS.get(i);
            ApplyHandover applyHandover=new ApplyHandover();
            BeanUtils.copyProperties(ay,applyHandover);
            String materialNo = materialVO.getMaterialNo();
            applyHandover.setMaterialNo(materialNo);
            String name = materialVO.getName();
            applyHandover.setMaterialName(name);
            applyHandover.setStatus(0);
            applyHandover.setImg(materialVO.getImg());

            applyHandover.setAdminUserId(adminUser.getId());
            applyHandover.setAdminUserName(adminUser.getUserName());
            applyHandover.setHandoverPersonUserId(handoverPersonUserId);
            String handoverPersonUserName = handoverPersonUser.getUserName();
            applyHandover.setHandoverPersonUserName(handoverPersonUserName);
            //交接单会生产2并交接单 需要管理员,
            String  extApplyNo= CodeUtils.generateShortUuid();
            //第一个订单的ext的第二个订单的订单号
            ay.setExt(extApplyNo);
            ay.setMaterialNo(materialNo);
            ay.setMaterialName(name);
            applyHandoverMapper.insert(applyHandover);
            applyMapper.insertSelective(ay);
            String applyNo = CodeUtils.generateApplyNo(ApplyTypeMatericalEnum.HANDOVERL.getValue());
            ay.setId(null);
            ay.setApplyNo(applyNo);
            ay.setExt(extApplyNo);
            applyMapper.insertSelective(ay);
        }
        return true;
    }

    @Override
    public Apply create() {
        Apply apply = super.create();
        apply.setApplyNo(CodeUtils.generateApplyNo(ApplyTypeMatericalEnum.HANDOVERL.getValue()));
        return apply;
    }

    private  List<MaterialVO> checkMaterialNos(String[] split ){
        String s = CommonStringUtils.toStrNotQuotationMarks(split);
        List<MaterialVO> materialVOS = materialMapper.listMaterialVOByMaterialNos(s);

        return  materialVOS;
    }

}
